window.addEventListener('load', function () {
    let tbody = document.querySelector('tbody')
    let btnsutdent = document.querySelector('.btnsutdent')///添加学员弹框
    let form = document.querySelector('#addModal form') ///form 表单
    let btnreset = document.querySelector('.btnreset') ///重置按钮

    let provinceEle = document.querySelector('#addModal [name="province"]')///省
    let cityEle = document.querySelector('#addModal [name="city"]')/// 市
    let countyEle = document.querySelector('#addModal [name="county"]')///县
    let addModalLabel = document.querySelector('#addModalLabel')///添加学员的文本
    let btnTj = document.querySelector('.btnTj')///添加按钮
    let name = document.querySelector('[name="name"]')/// 姓名
    let age = document.querySelector('[name="age"]')/// 年龄
    let phone = document.querySelector('[name="phone"]')/// 手机号
    let salary = document.querySelector('[name="salary"]')/// 期望薪资
    let truesalary = document.querySelector('[name="truesalary"]')/// 实际薪资
    let sex = document.querySelectorAll('[name="sex"]')/// 性别
    let group = document.querySelector('[name="group"]')/// 组号




    // console.log(provinceEle, cityEle, countyEle);
    ///--------------------渲染-----------------
    function init() {
        axios({
            url: '/student/list'
        }).then(res => {
            console.log(res);
            let htmlSrc = ''
            res.data.data.forEach(function (value, index) {
                htmlSrc += `  <tr>
                <th scope="row">${index + 1}</th>
                <td>${value.name}</td>
                <td>${value.age}</td>
                <td>${value.sex}</td>
                <td>${value.group}</td>
                <td>${value.phone}</td>
                <td>${value.salary}</td>
                <td>${value.truesalary}</td>
                <td>${value.province + value.city + value.county}</td>
                <td>
                  <button type="button" data-id="${value.id}" class="btn btn-primary btn-sm btnup ">修改</button>

                  <button type="button" data-id="${value.id}" class="btn btn-danger btn-sm btndel " >删除</button>
                </td>
              </tr>`
            })
            tbody.innerHTML = htmlSrc
        })
    }
    init()
    ///--------------------验证-----------------

    function student() {
        return {
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空',
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度2~10位'
                        }
                    }
                },
                age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空',
                        },
                        greaterThan: {
                            value: 18,
                            message: '年龄不能小于18岁'
                        },
                        lessThan: {
                            value: 60,
                            message: '年龄不能超过60岁'
                        }
                    }
                },
                sex: {
                    validators: {
                        choice: {
                            min: 1,
                            max: 1,
                            message: '请选择性别'
                        }
                    }
                },
                group: {
                    validators: {
                        notEmpty: {
                            message: '组号不能为空',
                        },
                        regexp: {
                            regexp: /^\d{1,2}$/,
                            message: '请选择有效的组号'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空',
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请填写有效的手机号'
                        }
                    }
                },
                salary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '期望薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '期望薪资不能高于100000'
                        }
                    }
                },
                truesalary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '实际薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '实际薪资不能高于100000'
                        }
                    }
                },
                province: {
                    validators: {
                        notEmpty: {
                            message: '省份必填',
                        },
                    }
                },
                city: {
                    validators: {
                        notEmpty: {
                            message: '市必填',
                        },
                    }
                },
                county: {
                    validators: {
                        notEmpty: {
                            message: '县必填',
                        },
                    }
                },
            }
        }
    }

    ///--------------------弹出添加学院模态框-----------------

    btnsutdent.addEventListener('click', function () {
        addModalLabel.innerText = '新增学员'
        btnTj.innerText = '确认添加'

        btnreset.click()
        cityEle.innerHTML = `<option selected value="">--市--</option>`
        countyEle.innerHTML = `<option selected value="">--县--</option>`

        $('#addModal').modal('show')
    })

    ///-------------------获取省市县-----------------
    /// 1 ----省----

    axios({
        url: '/geo/province'
    }).then(res => {
        console.log(res);
        let htmlSrc = `<option selected value="">--省--</option>`
        res.data.forEach(function (value) {
            // console.log(value);
            htmlSrc += `<option  value="${value}">${value}</option>`
            provinceEle.innerHTML = htmlSrc
        })
    })

    /// 2 ----市----

    provinceEle.addEventListener('change', function () {
        let pname = provinceEle.value

        if (!pname) {
            cityEle.innerHTML = `<option selected value="">--市--</option>`
            countyEle.innerHTML = `<option selected value="">--县--</option>`
            return
        }
        axios({
            url: '/geo/city',
            params: { pname }
        }).then(res => {
            // console.log(res);
            let htmlSrc = `<option selected value="">--省--</option>`
            res.data.forEach(function (value) {
                // console.log(value);
                htmlSrc += `<option  value="${value}">${value}</option>`
                cityEle.innerHTML = htmlSrc
            })
        })
    })

    /// 3 ----县----

    cityEle.addEventListener('change', function () {
        let pname = provinceEle.value
        let cname = cityEle.value

        if (!cname) {
            countyEle.innerHTML = `<option selected value="">--县--</option>`
            return
        }
        // console.log(pname, cname);
        axios({
            url: '/geo/county',
            params: {
                pname,
                cname
            }
        }).then(res => {
            // console.log(res);
            let htmlSrc = `<option selected value="">--省--</option>`
            res.data.forEach(function (value) {
                // console.log(value);
                htmlSrc += `<option  value="${value}">${value}</option>`
                countyEle.innerHTML = htmlSrc
            })
        })
    })

    ///-------------------新增学员-----------------

    $('#addModal form')
        .bootstrapValidator(student())
        .on('success.form.bv', function (e) {
            e.preventDefault();

            let formdata = new FormData(form)
            let data = {}
            formdata.forEach(function (value, key) {
                data[key] = value
            })
            console.log(data);

            if (addModalLabel.innerText === '新增学员') {
                axios({
                    url: '/student/add',
                    method: 'POST',
                    data
                }).then(res => {
                    console.log(res);
                    if (res.data.code == 0) {
                        $('#addModal').modal('hide')
                        toastr.success(res.data.message)
                        btnreset.click()

                    }
                    init()
                })
            } else {
                data.id = newid
                axios({
                    url: '/student/update',
                    method: 'put',
                    data
                }).then(res => {
                    console.log(res);
                    if (res.data.code == 0) {
                        $('#addModal').modal('hide')
                        toastr.success(res.data.message)
                        btnreset.click()
                    }
                    init()
                })

            }
        });

    ///-------------------删除-----------------
    tbody.addEventListener('click', function (e) {
        if (e.target.classList.contains('btndel')) {
            if (confirm('你确定删除吗')) {

                let id = e.target.dataset.id
                console.log(id);

                axios({
                    url: '/student/delete',
                    method: 'DELETE',
                    params: {
                        id
                    }
                }).then(res => {
                    console.log(res);
                    if (res.data.code == 0) {
                        toastr.success(res.data.message)
                    }
                    init()
                })
            }

        }
    })
    ///-------------------修改  弹出模态框-----------------
    let newid
    tbody.addEventListener('click', function (e) {
        if (e.target.classList.contains('btnup')) {

            addModalLabel.innerText = '修改学员'
            btnTj.innerText = '确认修改'
            let id = e.target.dataset.id
            newid = id
            axios({
                url: '/student/one',
                params: { id }
            }).then(res => {
                let data = res.data.data
                console.log(data);
                //.取值
                name.value = data.name
                age.value = data.age
                phone.value = data.phone
                salary.value = data.salary
                truesalary.value = data.truesalary
                group.value = data.group


                //.复选框的取值
                data.sex === '男' ? (sex[0].checked = true) : (sex[1].checked = true)

                //.省市县 （下拉列表）的取值
                provinceEle.value = data.province
                cityEle.innerHTML = `<option selected value="${data.city}">${data.city}</option>`
                countyEle.innerHTML = `<option selected value="${data.county}">${data.county}</option>`


                $('#addModal').modal('show')
            })
        }
    })










})